/* eslint-disable react/no-array-index-key */
/* eslint-disable react/jsx-indent */
import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Modal, Row, Col, Select, Input, Button, Table } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import Area from '../../components/Area';
import DictCode from '../../components/DictCode';

const FormItem = Form.Item;
const { Option } = Select;
@connect(({ socialinsurancehadpay, loading }) => ({
  socialinsurancehadpay,
  loading: loading.effects['socialinsurancehadpay/fetchNoBillEmpDet'],
}))
@Form.create()
class CreateBillModal extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      billMonthArr: [],
      nowPage: 1,
      pageSizes: 10,
    };
  }

  componentDidMount() {
    this.getDateArr();
  }

  getList(nowPage = 1, pageNum = 10) {
    // 参数：{a,b,c,d,e,nowPage,pageNum}
    const { form, dispatch, type } = this.props;
    const { billDate } = this.state;
    this.setState({
      selectedRowKeys: [],
    });
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const pageArg = {
        currentPage: nowPage,
        pageSize: pageNum,
      };
      const params = { type, inParam: { pageArg, ...fieldsValue, billYm: billDate } };
      dispatch({
        type: 'socialinsurancehadpay/fetchNoBillEmpDet',
        payload: params,
      });
    });
  }

  handleCancel = () => {
    const { form } = this.props;
    const { onCancel } = this.props;
    onCancel();
    this.getDateArr();
    form.resetFields();
  };

  reset = () => {
    const { form } = this.props;
    form.resetFields();
  };

  getInParam = () => {
    let inParam = {};
    const { selectedRowKeys, billDate } = this.state;
    const { form } = this.props;
    if (selectedRowKeys.length) {
      inParam = { billYm: billDate, accoIdArr: selectedRowKeys };
    } else {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        inParam = { billYm: billDate, ...fieldsValue };
      });
    }
    return inParam;
  };

  handleOk = () => {
    const { onOk } = this.props;
    const inParam = this.getInParam();
    if (inParam.accoIdArr) {
      onOk(inParam);
    } else {
      Modal.confirm({
        title: `您当前未选中任何账户，默认为所有账户创建账单，是否继续？`,
        icon: <ExclamationCircleOutlined />,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          onOk(inParam);
        },
      });
    }
  };

  next = () => {
    const { nextClick = () => {} } = this.props;
    nextClick();
    this.setState({
      nowPage: 1,
      pageSizes: 10,
      selectedRowKeys: [],
    });
    this.getList(1, 10);
  };

  dateChange = value => {
    this.setState({
      billDate: value,
    });
  };
  // 查询

  goSearch = () => {
    const { pageSizes } = this.state;
    this.setState({
      nowPage: 1,
    });
    this.getList(1, pageSizes);
  };

  // 生成账单中的账单年月
  getDateArr = () => {
    const nowDate = moment(new Date()).format('YYYYMM');

    const d = new Date();
    d.setDate(1);
    d.setMonth(d.getMonth() + 1);
    const yy1 = d.getFullYear();
    let mm1 = d.getMonth() + 1; // 因为getMonth（）返回值是 0（一月） 到 11（十二月） 之间的一个整数。所以要给其加1
    if (mm1 < 10) {
      mm1 = `0${mm1}`;
    }
    const nextDate = `${yy1}${mm1}`;
    const arr = [];
    arr.push(nowDate);
    arr.push(nextDate);
    this.setState({
      billMonthArr: arr,
      billDate: nowDate,
    });
  };

  render() {
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 16 } },
    };
    const {
      form: { getFieldDecorator },
      type,
      footerVisible,
      visible,
      loading,
      confirmLoading,
      socialinsurancehadpay: { noDataSource, noCmTotal },
    } = this.props;
    const { selectedRowKeys, nowPage, pageSizes, billDate, billMonthArr } = this.state;
    // 表格配置 -
    const columns = [
      {
        title: '缴纳方式',
        dataIndex: 'payWayName',
        align: 'center',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'center' } }),
      },
      {
        title: '执行地',
        dataIndex: 'declAreaName',
        align: 'center',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'center' } }),
      },
      {
        title: '账户名称',
        dataIndex: Number(type) === 1 ? 'insAccoName' : 'accuAccoName',
        align: 'center',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'center' } }),
      },
    ];
    // 表格  选择功能配置
    const rowSelection = {
      selectedRowKeys,
      onChange: selectedKeys => {
        this.setState({ selectedRowKeys: selectedKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.age === '1000', // Column configuration not to be checked
        name: record.name,
      }),
    };
    const billTable = {
      columns,
      dataSource: noDataSource,
      rowSelection,
      bordered: false,
      loading,
      pagination: {
        defaultCurrent: 1, // 默认当前页
        defaultPageSize: 10, // 默认单页条数
        current: nowPage, // 当前页
        pageSize: pageSizes, // 单页条数
        total: noCmTotal, // 数据总数
        showQuickJumper: true, // 跳转到某一页
        onChange: (page, pageSize) => {
          this.setState({ nowPage: page }); // 页码改变的回调
          this.getList(page, pageSize);
        },
        showSizeChanger: true,
        onShowSizeChange: (current, size) => {
          // 单页条数变化的回调
          this.setState({ nowPage: 1, pageSizes: size });
          this.getList(1, size);
        },
        showTotal: total => {
          const totalPage1 =
            total < billTable.pagination.pageSize
              ? 1
              : Math.ceil(total / billTable.pagination.pageSize);
          return `共 ${total} 条记录 第 ${nowPage} / ${totalPage1}页`;
        },
      },
      rowKey: record => (Number(type) === 1 ? record.insAccoId : record.accuAccoId), // 这里防止行重复
    };
    return (
      <Modal
        title={footerVisible ? '请选择账户' : '生成账单'}
        visible={visible}
        destroyOnClose
        onCancel={this.handleCancel}
        width={footerVisible ? 800 : 600}
        footer={
          footerVisible
            ? [
                <Button key="back" onClick={this.handleCancel}>
                  关闭
                </Button>,
                <Button
                  key="submit"
                  type="primary"
                  loading={confirmLoading}
                  onClick={this.handleOk}
                  disabled={!noCmTotal}
                >
                  确定
                </Button>,
              ]
            : null
        }
      >
        {!footerVisible ? (
          <div>
            <FormItem {...formItemLayout} label="账单年月">
              <Select onChange={this.dateChange} value={billDate} style={{ width: 200 }}>
                {billMonthArr.map((value, index) => (
                  <Option value={value} key={index}>
                    {value}
                  </Option>
                ))}
              </Select>
            </FormItem>
            <Row>
              <Col offset={3}>注：账单已生成但未回盘，可更新对应的账单数据；</Col>
            </Row>
            <Row>
              <Col offset={3}>已回盘或已回盘有差异的账单数据，不能更新账单。</Col>
            </Row>
            <Row
              style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                marginTop: 20,
                marginBottom: 20,
              }}
            >
              <Button type="primary" onClick={this.next}>
                下一步
              </Button>
            </Row>
          </div>
        ) : (
          <div>
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayout} label="执行地">
                  {getFieldDecorator('declAreaId')(<Area style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout} label="缴费方式">
                  {getFieldDecorator('payWay', {
                    rules: [{ required: false }],
                  })(<DictCode dictType="PAY_FEES_WAY" style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              {Number(type) === 1 ? (
                <Col span={12}>
                  <FormItem {...formItemLayout} label="账户名称">
                    {getFieldDecorator('insAccoName', {
                      rules: [{ required: false }],
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              ) : (
                <Col span={12}>
                  <FormItem {...formItemLayout} label="账户名称">
                    {getFieldDecorator('accuAccoName', {
                      rules: [{ required: false }],
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              )}
              <Col span={12}>
                <Button
                  type="primary"
                  style={{ marginLeft: '20px', marginTop: '4px' }}
                  onClick={this.goSearch}
                >
                  查询
                </Button>
                <Button style={{ marginLeft: '20px', marginTop: '4px' }} onClick={this.reset}>
                  重置
                </Button>
              </Col>
            </Row>
            <Table {...billTable} style={{ marginTop: '20px' }} />
          </div>
        )}
      </Modal>
    );
  }
}

export default CreateBillModal;
